/* eslint-disable */

function BaiduMap(containerId, longitude, latitude, zoom, callback) {
  var o = $('#' + containerId);
  var s = 'CustomBaiduContainerId' + BaiduMap.mapCounter;
  var c = $('<div id="CustomBaiduContainerId' + BaiduMap.mapCounter + '">');
  BaiduMap.mapCounter += 1;
  c.width(o.width());
  c.height(o.height());
  o.html('');
  c.appendTo(('#' + containerId));
  this.containerId = containerId;
  this.mp = new BMap.Map(s);
  this.centerPoint = new BMap.Point(longitude, latitude);
  zoom = zoom || 18;
  this.mp.centerAndZoom(this.centerPoint, zoom);
  this.mp.enableScrollWheelZoom(true);

  var baseUri = '/images';
  this.pathIcon = new BMap.Icon(baseUri + '/path-point.png', new BMap.Size(10, 10));
  this.missionIcon = new BMap.Icon(baseUri + '/mission-point.png', new BMap.Size(20, 20));
  this.warningIcon = new BMap.Icon(baseUri + '/warning-point.png', new BMap.Size(20, 20));
  this.emergencyIcon = new BMap.Icon(baseUri + '/emergency-point.png', new BMap.Size(20, 20));

  this.paths = {};
  this.customPath = {};
  this.currentCustomPath = [];
  this.lines = {};
  this.robots = {};
  this.missions = {};
  this.warnings = {};
  this.current = [];

  this.setCurrent = function (t) {
  };

  var onTitlesloaded = function() {
    this.mp.removeEventListener('tilesloaded', onTitlesloaded);
    // this.baiduContainer = $('#' + s).detach();
    // this.baiduContainer.appendTo(o);
    if(callback) callback(this);
  }.bind(this);

  this.mp.addEventListener('tilesloaded', onTitlesloaded);


  this.mp.addEventListener('click', function(e) {
    eve('map.click', this, {x: e.point.lng, y: e.point.lat});
  });
  // add custom BMap.Marker prototype
  BMap.Marker.prototype.data = function(property, value) {
    if(arguments.length > 1) {
      this[property] = value;
    } else {
      return this[property];
    }
  };

  // BMap.Marker.prototype.remove = function() {
  //   this.getMap().removeOverlay(this);
  // };

  BaiduMap.instance = this;
}

BaiduMap.mapCounter = 0;

BaiduMap.Robot = function (map, id, name, type, position) {
  if (!(this instanceof BaiduMap.Robot)) return new BaiduMap.Robot(map, id, name, type, position);

  var robotImg;
  var robotActiveImg;
  var baseUri = '/images';
  if (type === 'SSR') {
    robotImg = baseUri + '/r2.png';
    robotActiveImg = baseUri + '/r2-active.png';
  } else {
    robotImg = baseUri + '/r1.png';
    robotActiveImg = baseUri + '/r1-active.png';
  }
  var icon = new BMap.Icon(robotImg, new BMap.Size(50, 50), {imageSize: new BMap.Size(50,50)});
  var iconActive = new BMap.Icon(robotActiveImg, new BMap.Size(50, 50), {imageSize: new BMap.Size(50,50)});
  var point = new BMap.Point(position.x, position.y);
  this.robot = new BMap.Marker(point);
  this.robot.setIcon(icon);
  // map.mp.addOverlay(this.robot);
  this.robot.data('id', id);
  this.robot.data('name', name);
  this.actived = false;

  this.robot.addEventListener('click', (function () {
    for(var ri in map.robots) {
      var r = map.robots[ri];
      r && r !== this && r.normal();
    }
    this.active();
    eve('robot.click', this.robot, this.robot.data('id'));
  }).bind(this));

  var jo = $(this.robot.initialize(map.mp));
  jo.popover({ container: 'body', viewport: $(this.robot.V), trigger: 'hover', title: name ? name : $.i18n.prop('SrosMap_robot_name', id), content: $.i18n.prop('SrosMap_robot_stat_running') });
  jo.on('shown.bs.popover', function () {
    this.data('popoverShown', true);
  }.bind(this.robot));
  jo.on('hidden.bs.popover', function () {
    this.data('popoverShown', false);
  }.bind(this.robot));

  this.setJobName = function(mission) {
    var content;
    if (mission.length === 0) {
        content = $.i18n.prop('SrosMap_robot_stat_running');
    } else {
        content = $.i18n.prop('SrosMap_robot_stat_exec_mission', mission);
    }
    jo.attr('data-content', content);
  };

  this.active = function () {
    this.robot.setIcon(iconActive);
    // $(this.robot.V).popover('show');
    this.actived = true;
  };

  this.normal = function () {
    this.robot.setIcon(icon);
    // $(this.robot.V).popover('hide');
    this.actived = false;
  };

  this.remove = function () {
    if (this.robot.data('popoverShown')) {
      $(this.robot.V).popover('destroy');
    }
    // this.robot.remove();
    this.robot.getMap().removeOverlay(this.robot);
    this.robot = null;
  };

  this.move = function (x, y) {
    this.robot.setPosition(new BMap.Point(x, y));
    if (this.robot.data('popoverShown')) {
      $(this.robot.V).popover('show');
    }
  };

  this.isActive = function () {
    return this.actived;
  };

  return this;
};

BaiduMap.prototype.removeAll = function () {
    this.removeIntervention()
        .removeAllWarnings()
        .removeAllCustomPaths()
        .removeAllMissions()
        .removeAllRobots()
        .removeAllPaths();
};

BaiduMap.prototype.hide = function() {
    var s = '#' + this.containerId + ' > #CustomBaiduContainerId';
    this.removeAll();
    // $(s).remove();
    // $(this.mp.getContainer()).hide();
    if (!this.baiduContainer) {
        this.baiduContainer = $(s).detach();
    }
};

BaiduMap.prototype.show = function (containerId, longitude, latitude, zoom, callback) {
    // var c = $('#' + containerId);
    // c.html('');
    // this.baiduContainer.appendTo(c);
    var c = $('#' + this.containerId + ' > #CustomBaiduContainerId');
    if (!c.length) {
      // $(this.mp.getContainer()).appendTo('#' + this.containerId);
      this.baiduContainer.appendTo('#' + this.containerId);
      this.baiduContainer.hide();
    }
    // $('#' + this.containerId + ' > #CustomBaiduContainerId').show(10, function(){
    // $(this.mp.getContainer()).show(500, function(){
    this.baiduContainer.show(500, function(){
    // var onTitlesloaded = function() {
      this.centerPoint = new BMap.Point(longitude, latitude);
      zoom = zoom || 18;
      this.mp.panTo(this.centerPoint);
      this.mp.setZoom(zoom);
      // this.mp.removeEventListener('tilesloaded', onTitlesloaded);
      if(callback) callback(this);
    // }.bind(this);
    }.bind(this));
    // this.mp.addEventListener('tilesloaded', onTitlesloaded);
    // this.baiduContainer = null;
};

BaiduMap.prototype.panTo = function (position) {
  var point = new BMap.Point(position.x, position.y);
  // this.mp.panTo(point);
  this.mp.centerAndZoom(point, 18);
  return this;
};

BaiduMap.prototype.setMassPath = function(id, path, orgColor) {
  var points = [];
  for (var i = 0; i < path.length; i += 1) {
    var p = path[i];
    points.push(new BMap.Point(p.x, p.y));
  }
  var options = {
    color: orgColor,
    size: BMAP_POINT_SIZE_SMALL,
  };
  var pointCollection = // new BMap.PointCollection(points, options);
  new BMap.Polyline(points, {strokeColor:"blue", strokeWeight:3, strokeOpacity:0.5});
  pointCollection.addEventListener('click', function (e) {
    eve('path.click',pointCollection, { x: e.point.lng, y: e.point.lat});  // 监听点击事件
  });
  this.mp.addOverlay(pointCollection);
  this.paths[id] = pointCollection;
  this.paths[id].type__ = 'mass';
  this.paths[id].length = path.length;

  return this;
};

BaiduMap.prototype.setPath = function (id, path, orgColor) {
  this.removePath(id);

  var color = orgColor || '#00f';
  if (path.length > 0) {
    return this.setMassPath(id, path, color);
  }
  for (var i = 0; i < path.length; i += 1) {
    var p = path[i];
    var point = new BMap.Point(p.x, p.y);
    var t = new BMap.Marker(point);
    t.setIcon(this.pathIcon);
    t.data('posi', p);
    t.addEventListener('click', (function () {
      eve('path.click', this, this.data('posi'));
    }).bind(t));

    this.mp.addOverlay(t);

    var ct = 'position: x: ' + p.x + ',y: ' + p.y;
    var pop = { container: 'body', html: true, trigger: 'hover', title: 'path ' + id, content: ct };
    t.data('popover', pop);
    $(t.V).popover(pop);
    t.setTitle(ct);
    this.paths[id].push(t);
  }
  // var markerClusterer = new BMapLib.MarkerClusterer(this.mp, {markers:this.paths[id]});
  // this.paths[id].attr('fill', color);
  // this.paths[id].data('fillColor', color);

  // this.lines[id] = this.paper.path(lineStr);
  // this.lines[id].attr('stroke', color);

  // this.paths[id].toFront();

  return this;
};

BaiduMap.prototype.removePath = function (id) {
  if (this.paths[id] && this.paths[id].length > 0) {
    if (this.paths[id].type__ === 'mass') {
      this.mp.removeOverlay(this.paths[id]);
    } else {
      this.paths[id].forEach(function(p) {
        // p.remove();
        this.mp.removeOverlay(p);
      });
    }
  }
  this.paths[id] = [];
  if (this.lines[id]) this.lines[id].remove();

  return this;
};

BaiduMap.prototype.removeAllPaths = function () {
    for (var w in this.paths) {
        if (Object.prototype.hasOwnProperty.call(this.paths, w)) {
            this.removePath(w);
        }
    }
    this.paths = {};
    this.lines = {};

    return this;
};

BaiduMap.prototype.setRobot = function (id, name, robotType, position) {
  if (this.robots[id]) {
    this.removeRobot(id);
  }
  this.robots[id] = new BaiduMap.Robot(this, id, name, robotType, position);
  
  return this;
};

BaiduMap.prototype.setRobotJobName = function (id, name) {
  if (this.robots[id]) {
    this.robots[id].setJobName(name);
  }

  return this;
};

BaiduMap.prototype.setActiveRobot = function (id) {
  if (this.robots[id]) {
    for (var ri in this.robots) {
        var r = this.robots[ri];
        r && r.normal();
    }
    this.robots[id].active();
  }
};

BaiduMap.prototype.removeRobot = function (id) {
  if (this.robots[id]) {
    // if (this.robots[id].data('popoverShown')) {
    //   $(this.robots[id].node).popover('destroy');
    // }
    this.robots[id].remove();
    this.robots[id] = null;
  }
  
  return this;
};

BaiduMap.prototype.removeAllRobots = function () {
    for (var w in this.robots) {
        if (Object.prototype.hasOwnProperty.call(this.robots, w)) {
            this.removeRobot(w);
        }
    }
    this.robots = {};

    return this;
};

BaiduMap.prototype.moveRobotPosition = function (id, position, convert) {
  if (this.robots[id]) {
        // $(this.robots.id.node).popover('hide');
    // this.robots[id].attr('x', position.x);
    // this.robots[id].attr('y', position.y);
    // if (this.robots[id].data('popoverShown')) {
    //   $(this.robots[id].node).popover('show');
    // }
    // this.robots[id].setPosition(new BMap.Point(position.x, position.y));
    var robot = this.robots[id];
    if(convert == null) {
      convert = true;
    }
    if(convert) {
      var convertor = new BMap.Convertor();
      var p = new BMap.Point(position.x, position.y);
      convertor.translate([p], 1, 5, function (data) {
        if (data.status === 0) {
          robot.move(data.points[0].lng, data.points[0].lat);
        }
      });
    } else {
      robot.move(position.x, position.y);
    }
  }

  return this;
};

function baiduMapSetMissionEvent(e) {
  eve('path.setMission', this, e);
}

BaiduMap.prototype.startSetMission = function () {
  this.isStartSetMission = true;
  this.on('path.click', baiduMapSetMissionEvent);

  return this;
};
BaiduMap.prototype.stopSetMission = function () {
  this.unbind('path.click', baiduMapSetMissionEvent);
  this.isStartSetMission = false;

  return this;
};

BaiduMap.prototype.getCircle = function (pathId, x, y) {
  if (this.paths[pathId].type__ === 'mass') return null;
  var path = this.paths[pathId];
  for (var i = 0; i < path.length; i += 1) {
    var p = path[i].data('posi');
    if (p.x === x && p.y === y) {
      return path[i];
    }
  }
  return null;
};

BaiduMap.prototype.setMission = function (id, t) {
  if (!this.isStartSetMission) return this;
  this.removeMission(id);
  t.data('missionId', id);
  t.setIcon(this.missionIcon);
  this.missions[id] = t;

  return this;
};

BaiduMap.prototype.setMissionByXY = function (id, x, y) {
  var t = null;
  // for (var pid in this.paths) { // eslint-disable-line
  //   if (Object.prototype.hasOwnProperty.call(this.paths, pid)) {
  //     t = this.getCircle(pid, x, y);
  //     if (t) break;
  //   }
  // }
  if (!t) {
    var point = new BMap.Point(x, y);
    t = new BMap.Marker(point);
    t.setIcon(this.pathIcon);
    this.mp.addOverlay(t);
    t.data('posi', {x: x, y: y});
    t.addEventListener('click', (function () {
      eve('mission.click', this, this.data('posi'));
    }).bind(t));

    this.mp.addOverlay(t);

    var ct = 'position: x: ' + x + ',y: ' + y;
    var pop = { container: 'body', html: true, trigger: 'hover', title: 'mission ' + id, content: ct };
    t.data('popover', pop);
    $(t.V).popover(pop);
  }
  if (t) {
    this.isStartSetMission = true;
    this.setMission(id, t);
    this.isStartSetMission = false;
  }

  return this;
};

BaiduMap.prototype.removeMission = function (id) {
  if (!this.isStartSetMission) return this;
  if (this.missions[id]) {
    $(this.missions[id].V).popover('destroy');
    this.mp.removeOverlay(this.missions[id]);
    this.missions[id] = null;
  }

  return this;
};

BaiduMap.prototype.removeMissionByXY = function (id, x, y) {
  // var t;
  // for (var pid in this.paths) { // eslint-disable-line
  //   if (Object.prototype.hasOwnProperty.call(this.paths, pid)) {
  //     t = this.getCircle(pid, x, y);
  //     if (t) break;
  //   }
  // }
  // if (t && this.missions[id] === t) {
  if (this.missions[id]) {
    this.isStartSetMission = true;
    this.removeMission(id);
    this.isStartSetMission = false;
  }

  return this;
};

BaiduMap.prototype.removeAllMissions = function () {
    this.isStartSetMission = true;
    for (var w in this.missions) {
        if (Object.prototype.hasOwnProperty.call(this.missions, w)) {
            this.removeMission(w);
        }
    }
    this.isStartSetMission = false;
    this.missions = {};

    return this;
};

function setBaiduCustomPathHandle(e) {
  // var p = {x: e.point.lng, y: e.point.lat};
  var point = new BMap.Point(e.x, e.y);
  var t = new BMap.Marker(point);
  t.setIcon(this.pathIcon);
  t.data('posi', {x: e.x, y: e.y});
  this.currentCustomPath.push(t);
  this.mp.addOverlay(t);
}

BaiduMap.prototype.startCustomPath = function () {
  this.currentCustomPath = [];
  this.setCustomPathHandle = setBaiduCustomPathHandle.bind(this);
  this.on('map.click', this.setCustomPathHandle);

  return this;
};

BaiduMap.prototype.endCustomPath = function (id) {
  this.unbind('map.click', this.setCustomPathHandle);
  this.removeCustomPath(id);
  this.customPath[id] = this.currentCustomPath;
  var r = [];
  this.customPath[id].forEach(function(t) {
    r.push(t.data('posi'));
  });
  return r;
};

BaiduMap.prototype.removeCustomPath = function (id) {
  if (this.customPath[id] && this.customPath[id].length > 0) {
    this.customPath[id].forEach(function(p) {
      // p.remove();
      this.mp.removeOverlay(p);
    });
    this.customPath[id] = null;
  }

  return this;
};

BaiduMap.prototype.removeAllCustomPaths = function () {
    for (var w in this.customPath) {
        if (Object.prototype.hasOwnProperty.call(this.customPath, w)) {
            this.removeCustomPath(w);
        }
    }
    this.customPath = {};

    return this;
};

BaiduMap.prototype.setIntervention = function (x, y) {
  this.removeIntervention();
  var t;
  for (var pid in this.paths) { // eslint-disable-line
    if (Object.prototype.hasOwnProperty.call(this.paths, pid)) {
      t = this.getCircle(pid, x, y);
      if (t) break;
    }
  }
  if (!t) {
    var point = new BMap.Point(x, y);
    t = new BMap.Marker(point);
    t.setIcon(this.emergencyIcon);
    this.mp.addOverlay(t);
    t.data('SSR', true);
  }
  this.intervaentionSchedule = t;
  this.setCurrent(this.intervaentionSchedule);

  return this;
};

BaiduMap.prototype.removeIntervention = function () {
  if (!this.intervaentionSchedule) return this;
  if (this.intervaentionSchedule.data('SSR')) {
    // this.intervaentionSchedule.remove();
    this.mp.removeOverlay(this.intervaentionSchedule);
  } else {
    var icon;
    if (this.intervaentionSchedule.data('missionId')) {
      icon = this.missionIcon;
    } else {
      icon = this.pathIcon;
    }
    this.intervaentionSchedule.setIcon(icon);
  }
  this.intervaentionSchedule = null;

  return this;
};

BaiduMap.prototype.setWarning = function (id, position, describe) {
  if (this.warnings[id]) {
    this.removeWarning(id);
  }
  var point = new BMap.Point(position.x, position.y);
  this.warnings[id] = new BMap.Marker(point);
  this.warnings[id].setIcon(this.warningIcon);
  this.mp.addOverlay(this.warnings[id]);
  this.warnings[id].data('id', id);

  this.warnings[id].addEventListener('click', (function () {
    eve('warning.click', this, this.data('id'));
  }).bind(this.warnings[id]));

  var jo = $(this.warnings[id].V);
  jo.popover({ container: 'body', viewport: $(this.warnings[id].V), trigger: 'click', title: 'warning ' + id, content: describe });
  jo.on('shown.bs.popover', function () {
    this.data('popoverShown', true);
  }.bind(this.warnings[id]));
  jo.on('hidden.bs.popover', function () {
    this.data('popoverShown', false);
  }.bind(this.warnings[id]));

  return this;
};

BaiduMap.prototype.removeWarning = function (id) {
  if (this.warnings[id]) {
    if (this.warnings[id].data('popoverShown')) {
      $(this.warnings[id].V).popover('destroy');
    }
    // this.warnings[id].remove();
    this.mp.removeOverlay(this.warnings[id]);
    this.warnings[id] = null;
  }

  return this;
};

BaiduMap.prototype.removeAllWarnings = function () {
  for (var w in this.warnings) {
    if (Object.prototype.hasOwnProperty.call(this.warnings, w)) {
      this.removeWarning(w);
    }
  }

  return this;
};

BaiduMap.prototype.on = eve.on;
BaiduMap.prototype.unbind = eve.unbind;
BaiduMap.prototype.listeners = eve.listeners;
